<?php
namespace Users\Model;

use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql;
use Zend\Db\Sql\Where;
use Zend\Db\Sql\Select;
use Zend\Paginator\Adapter\DbSelect;
use Zend\Paginator\Paginator;
use Zend\Db\Sql\Predicate;
use Zend\Db\Sql\Expression;

class UserRegionsTable
{
    protected $tableGateway;
	protected $select;
    public function __construct(TableGateway $tableGateway)
    {
        $this->tableGateway = $tableGateway;
		$this->select = new Select();
    }
	public function getuserregions($userid){
		$select = $this->tableGateway->getSql()->select();
		$select->join('country', 'user_regions.country_id=country.country_id',array('countryname'=>'nicename'),'left');		
		$select->where('user_id="'.$userid.'"');			
		$resultSet = $this->tableGateway->selectWith($select);
		return $resultSet;
	}
	public function addRegions( $user_id,$sessionRegions )
    {
		$deleteStatus=$this->tableGateway->delete(array('user_id' => $user_id));
		if( $deleteStatus >= 0 )
		{
			$regionRows=explode("!",$sessionRegions);
			foreach( $regionRows as $key=>$value )
			{
				$currentRegion = explode("-",$value);
				$country_id=$currentRegion[0];
				$data = array(
					'user_id' 	  	       => $user_id, 	
					'country_id' 		   => $country_id,
					'add_region_date' 	=> date('Y-m-d H:i:s'),
					'last_region_date' => date('Y-m-d H:i:s'),
					'regions_status' => 1,
				);	
				$insertresult=$this->tableGateway->insert($data);
			}
			return $insertresult;
		}
	}
	public function deleteRegions( $user_id )
    {
		$data = array(
			'regions_status'      	=>0,
		);
		$deleteRegionsStatus=$this->tableGateway->update($data, array('user_id' => $user_id));
		//$deleteRegionsStatus=$this->tableGateway->delete(array('user_id' => $user_id));
		return $deleteRegionsStatus;
	}

	public function getRegionsCount( $user_id )
    {
		$select = $this->tableGateway->getSql()->select();			
		$select->where( 'user_id='. $user_id );
		$resultSet = $this->tableGateway->selectWith($select);
		$existingRegionsCount = $resultSet->count();
		return $existingRegionsCount;
	}
	public function loadRegions( $user_id )
    {
		$select = $this->tableGateway->getSql()->select();			
		$select->join('country', 'user_regions.country_id=country.country_id',array('countryname'=>'nicename'),'left');
		$select->where( 'user_id='. $user_id );
		$resultSet = $this->tableGateway->selectWith($select);
		
		$loadedRegions = "";
		foreach( $resultSet as $resultRow )
		{
			$loadedRegions .= $resultRow->country_id . "-" . $resultRow->countryname . "!";
		}
		$loadedRegions = substr( $loadedRegions,0,(strlen($loadedRegions)-1) ); 
		return $loadedRegions;
	}
}